<template>
  <el-dialog
    v-model="visible"
    :title="$t('pageVirtualMedia.modal.title')"
    width="500"
    @close="resetForm"
    @open="initModal"
  >
    <el-form :model="form" :rules="rules">
      <el-form-item
        :label="$t('pageVirtualMedia.modal.serverUri')"
        :label-width="formLabelWidth"
        prop="serverUri"
      >
        <el-input v-model="form.serverUri" autocomplete="off" />
      </el-form-item>
      <el-form-item
        :label="$t('pageVirtualMedia.modal.username')"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item
        :label="$t('pageVirtualMedia.modal.password')"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="RW" :label-width="formLabelWidth">
        <el-switch v-model="form.isRW" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onOk">{{ $t('global.action.cancel') }}</el-button>
        <el-button type="primary" @click="closeModal">
          {{ $t('global.action.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useVuelidateTool from '@/hooks/useVuelidateTool';

const { useVuelidate, required, elementInputValidator } = useVuelidateTool();
const props = defineProps<{ connection: Object }>();
const emit = defineEmits(['ok']);

const visible = ref(false);
const formLabelWidth = '140px';

const form = reactive({
  serverUri: null,
  username: null,
  password: null,
  isRW: false,
});
const v$ = useVuelidate(
  {
    serverUri: {
      required,
    },
  },
  form,
);
const rules = computed(() => {
  return {
    serverUri: {
      trigger: 'change',
      validator: elementInputValidator.value(v$, 'serverUri'),
    },
  };
});

const handleSubmit = () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  let connectionData = {};
  Object.assign(connectionData, form);
  emit('ok', connectionData);
  closeModal();
};
const initModal = () => {
  if (props.connection) {
    Object.assign(form, props.connection);
  }
};
const closeModal = () => {
  nextTick(() => {
    visible.value = false;
  });
};
const resetForm = () => {
  form.serverUri = null;
  form.username = null;
  form.password = null;
  form.isRW = false;
  v$.value.$reset();
};
const onOk = (bvModalEvt: { preventDefault: () => void }) => {
  bvModalEvt.preventDefault();
  handleSubmit();
};
</script>
